# 二进制精确修复脚本 - 使用严格的格式控制
import os
import shutil
import re

# 文件路径
original_file = r'd:\未知\yolo_apply\video_processing\video_processor.py'
final_backup = r'd:\未知\yolo_apply\video_processing\video_processor.py.final_backup'
temp_file = r'd:\未知\yolo_apply\video_processing\binary_precision.py'

# 确保我们使用最终备份
if os.path.exists(final_backup):
    print(f"Using binary approach with backup: {final_backup}")
    
    # 二进制模式读取文件内容
    with open(final_backup, 'rb') as f:
        binary_content = f.read()
    
    # 尝试解码内容
    try:
        text_content = binary_content.decode('utf-8')
    except UnicodeDecodeError:
        text_content = binary_content.decode('latin-1')
    
    # 规范化换行符
    text_content = text_content.replace('\r\n', '\n')
    text_content = text_content.replace('\r', '\n')
    
    # 按行分割
    lines = text_content.split('\n')
    
    # 找到问题区域
    start_line = None
    end_line = None
    
    for i, line in enumerate(lines):
        if '# 错误率过高时触发警告和恢复' in line:
            start_line = i
        elif start_line is not None and 'error_count = 0' in line:
            end_line = i
            break
    
    if start_line is not None and end_line is not None:
        print(f"Problem area identified: lines {start_line+1}-{end_line+1}")
        
        # 创建新的文件内容
        new_lines = []
        
        # 处理文件，逐行重写，确保正确的缩进
        in_process_loop = False
        base_indent = 0
        
        for i, line in enumerate(lines):
            stripped = line.strip()
            
            # 检查是否在_process_loop函数内
            if 'def _process_loop' in stripped and ':' in stripped:
                in_process_loop = True
                # 确定函数定义的缩进
                base_indent = len(line) - len(stripped)
                new_lines.append(' ' * base_indent + stripped)
                continue
            
            # 检查是否退出_process_loop函数
            if in_process_loop and stripped.startswith('def ') and ':' in stripped and not 'def _process_loop' in stripped:
                in_process_loop = False
                base_indent = len(line) - len(stripped)
                new_lines.append(' ' * base_indent + stripped)
                continue
            
            # 跳过问题区域内的行，但保留注释和重置
            if i >= start_line and i <= end_line:
                if i == start_line:
                    # 添加注释行，使用正确的缩进
                    if in_process_loop:
                        new_lines.append(' ' * (base_indent + 4) + '# 错误率过高时触发警告和恢复')
                    else:
                        new_lines.append(' ' * base_indent + '# 错误率过高时触发警告和恢复')
                elif i == end_line:
                    # 添加错误计数重置，使用正确的缩进
                    if in_process_loop:
                        new_lines.append(' ' * (base_indent + 4) + 'error_count = 0')
                    else:
                        new_lines.append(' ' * base_indent + 'error_count = 0')
                # 跳过其他行
                continue
            
            # 处理其他行
            if not stripped:
                # 空行保留
                new_lines.append('')
            elif in_process_loop:
                # 在_process_loop内的行，使用统一的4空格缩进
                if stripped.startswith('#'):
                    # 注释行
                    new_lines.append(' ' * (base_indent + 4) + stripped)
                else:
                    # 代码行
                    new_lines.append(' ' * (base_indent + 4) + stripped)
            else:
                # 不在_process_loop内的行，尝试保持原有缩进
                if stripped.startswith('class ') or stripped.startswith('def ') or stripped.startswith('if ') or stripped.startswith('for ') or stripped.startswith('while ') or stripped.startswith('try:') or stripped.startswith('except') or stripped.startswith('else:') or stripped.startswith('finally:'):
                    # 这些行可能有自己的缩进规则
                    line_indent = len(line) - len(stripped)
                    new_lines.append(' ' * line_indent + stripped)
                else:
                    # 普通行
                    new_lines.append(line)
        
        # 将新行列表重新组合为文本
        new_content = '\n'.join(new_lines)
        
        # 二进制模式写入文件，确保格式正确
        with open(temp_file, 'wb') as f:
            f.write(new_content.encode('utf-8'))
        
        print(f"Created precision binary fixed file: {temp_file}")
        
        # 替换原文件
        os.replace(temp_file, original_file)
        print(f"Replaced original file with precision fixed version")
        print("Now let's try to compile again...")
    else:
        print("Error: Could not locate the problem area in the file")
else:
    print(f"Error: Final backup file not found: {final_backup}")